package com.shengwei.truck.driver.utils;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.shengwei.truck.driver.R;

import java.lang.ref.WeakReference;

public class MyToast extends Toast {
    private static MyToast toast;

    public MyToast(Context context) {
        super(context);
    }

    /**
     * 展示toast在中间
     * @param contextWeakReference
     * @param tip:提示文字
     */
    public static void showToastCenter(WeakReference<Context> contextWeakReference, String tip,int duration,boolean isCenter){
        Context context = contextWeakReference.get();
        if(context != null){
            Toast toast = Toast.makeText(context, tip, duration);
            if(isCenter){
                toast.setGravity(Gravity.CENTER, 0, 0);
            }
            toast.show();
        }
    }




    public static void showText(Context context, CharSequence text) {
        showToast(context, text, Toast.LENGTH_LONG);
    }

    private static void showToast(Context context, CharSequence text, int time) {
        // 初始化一个新的Toast对象
        initToast(context, text);
        // 设置显示时长toast.setDur(time)
        // 显示Toast
        toast.show();
    }

    private static void initToast(Context context, CharSequence text) {
        try {
            cancelToast();
            toast = new MyToast(context);
            // 获取LayoutInflater对象
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // 由layout文件创建一个View对象
            View layout = inflater.inflate(R.layout.toast_layout, null);
            // 吐司上的文字
            TextView toast_text = (TextView) layout.findViewById(R.id.tvTip);
            toast_text.setText(text);
            toast.setView(layout);
            toast.setGravity(Gravity.CENTER, 0, 70);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 隐藏当前Toast
     */
    public static void cancelToast() {
        if (toast != null) {
            toast.cancel();
        }
    }

    public void cancel() {
        try {
            super.cancel();
        } catch (Exception e) {

        }
    }

    @Override
    public void show() {
        try {
            super.show();
        } catch (Exception e) {
        }
    }
}